<template>
  <div
    ref="scrollContainer"
    class="scroll-view scroll-view--horizontal hide-scrollbar overflow-x-auto"
  >
    <div
      class="flex items-center scroll-view__content"
      :class="tabClass.justifyContent"
    >
      <!-- 默认标签样式（原tabsType=1） -->
      <template v-if="!$slots.item">
        <div
          v-for="(tab, index) in tabs"
          :key="tab.id"
          :ref="el => setItemRef(el, index)"
          class="relative font-bold leading-40 h-40 text-14 text-center flex-shrink-0"
          :class="tabColor(tab, index)"
          @click="handleTabClick(tab.id)"
        >
          {{ tab.name }}
        </div>
      </template>

      <!-- 自定义标签内容插槽 -->
      <template v-else>
        <slot
          v-for="(tab, index) in tabs"
          :key="tab.id"
          name="item"
          :tab="tab"
          :index="index"
          :setItemRef="el => setItemRef(el, index)"
          :handleTabClick="() => handleTabClick(tab.id)"
        />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, watch, computed } from "vue";
import { TabItem } from "@/types";

const props = defineProps({
  // 分类项数据
  tabs: {
    type: Array as () => TabItem[],
    required: true,
    default: () => []
  },
  // 当前项 ID
  activeId: {
    type: String,
    required: true
  },
  // 禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 样式类
  tabClass: {
    type: Object,
    default: () => ({
      justifyContent: "",
      activeColor: "",
      itemWidth: "",
      textColor: "",
      textSize: "text-14",
      activeTextSize: "text-18"
    })
  }
});

const emit = defineEmits(["update:activeId"]);

// 使用计算属性返回颜色值
const tabColor = computed(() => (tab: TabItem, index: number) => {
  let tabColorStr = "";
  if (props.tabClass.itemWidth) {
    tabColorStr += " " + props.tabClass.itemWidth;
  }
  if (props.tabClass.textSize) {
    tabColorStr += " " + props.tabClass.itemWidth;
  }

  if (props.activeId === tab.id) {
    tabColorStr += ` is-active-type-1 ${props.tabClass.activeTextSize}`;
    if (props.tabClass.activeColor) {
      tabColorStr += " " + props.tabClass.activeColor;
    } else {
      tabColorStr += " text-2614FF";
    }
  } else {
    if (props.tabClass.textColor) {
      tabColorStr += " " + props.tabClass.textColor;
    }
  }
  if (props.tabClass.textSize) {
    tabColorStr += " " + props.tabClass.textSize;
  }
  if (index !== props.tabs.length - 1) {
    tabColorStr += " mr-20";
  }
  return tabColorStr;
});

// 滚动容器引用
const scrollContainer = ref<HTMLElement | null>(null);
// 分类项引用数组
const tabItems = ref<HTMLElement[]>([]);

// 设置分类项引用
const setItemRef = (el: any, index: number) => {
  if (el) {
    tabItems.value[index] = el;
  }
};

// 滚动到选中项（居中显示）
const scrollToActive = () => {
  if (!scrollContainer.value || tabItems.value.length === 0) return;

  const activeIndex = props.tabs.findIndex(tab => tab.id === props.activeId);
  if (activeIndex === -1) return;

  const activeItem = tabItems.value[activeIndex];
  if (!activeItem) return;

  const scrollView = scrollContainer.value;
  const scrollViewWidth = scrollView.clientWidth;
  const activeItemWidth = activeItem.offsetWidth;
  const activeItemOffsetLeft = activeItem.offsetLeft;

  // 计算滚动位置（居中）
  const scrollPosition =
    activeItemOffsetLeft - scrollViewWidth / 2 + activeItemWidth / 2;

  // 边界检查
  const maxScroll = scrollView.scrollWidth - scrollViewWidth;
  const safeScrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));

  // 设置滚动位置
  scrollView.scrollTo({
    left: safeScrollPosition,
    behavior: "smooth"
  });
};

// 点击选项卡
const handleTabClick = (id: string) => {
  if (props.disabled) return;
  emit("update:activeId", id);
  nextTick(() => {
    scrollToActive();
  });
};

// 监听活动 ID 变化
watch(
  () => props.activeId,
  () => {
    nextTick(() => {
      scrollToActive();
    });
  }
);

// 组件挂载后滚动到活动项
onMounted(() => {
  nextTick(() => {
    scrollToActive();
  });
});
</script>

<style scoped>
.is-active-type-1 {
  font-size: 18px;
}

.is-active-type-1::after {
  position: absolute;
  display: block;
  content: "";
  bottom: 6px;
  left: 50%;
  width: 30px;
  height: 7px;
  transform: translateX(-50%);
  background-image: url(https://kposshz-qncdn.ckjr001.com/admin/material/39_material_admin/image/home/tabs_normal_active_icon.png);
  background-size: 100% 100%;
  animation: showOpacity 0.15s ease-in;
}

@keyframes showOpacity {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
